package com.sunfeng.a03;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import org.springframework.stereotype.Component;

/**
 * @Author : 孙峰
 * @Description:
 * @Date : 2022/4/8  11:15
 */
@Slf4j
@Component
public class MyBeanPostProcessor implements InstantiationAwareBeanPostProcessor, DestructionAwareBeanPostProcessor {



    @Override
    public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
        if(beanName.equals("lifeCycleBean")){
            log.debug("<<<<<<<<<<< 实例化之前执行，这里返回的对象会替换掉原先的 bean");
        }
        return null;
    }

    @Override
    public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
        if(beanName.equals("lifeCycleBean")){
            log.debug("<<<<<<<<<<< 实例化之后执行,如果返回false 会跳过依赖注入阶段");
        }
        return true;
    }

    /**
     *  依赖注入阶段执行相应的操作
     * @param pvs
     * @param bean
     * @param beanName
     * @return
     * @throws BeansException
     */
    @Override
    public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) throws BeansException {
        if(beanName.equals("lifeCycleBean")){
                  log.debug("<<<<<<<<<<< 依赖注入阶段执行,@Autowire @Resource @Value");
        }
        return pvs;
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if(beanName.equals("lifeCycleBean")){
            log.debug("<<<<<<<<<<< 初始化之前执行，这里返回的对象会替换掉原先bean 如@PostConstruct @ConfigurationProperties");
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if(beanName.equals("lifeCycleBean")){
            log.debug("<<<<<<<<<<< 初始化之后执行，这里返回的对象会替换掉原来的bean， 如代理增强");
        }
        return bean;
    }
    @Override
    public void postProcessBeforeDestruction(Object bean, String beanName) throws BeansException {
        if(beanName.equals("lifeCycleBean")){
            log.debug("<<<<<<<<<<< 销毁之前执行，如 @PreDestroy");
        }
    }
}
